package com.uenpay.oem.ui.withdraw;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.socks.library.KLog;
import com.uenpay.im.ui.old.activity.pwd.SetPayPwdActivity;
import com.uenpay.im.utilities.ToastUtil;
import com.uenpay.im.utilities.Toasts;
import com.uenpay.oem.R;
import com.uenpay.oem.common.AppConstant;
import com.uenpay.oem.common.RxBusEventConstant;
import com.uenpay.oem.data.bean.UserTradePoundageInfo;
import com.uenpay.oem.ui.main.home.HomeNewFragment;
import com.uenpay.oem.ui.main.my.MyFragment;
import com.uenpay.oem.ui.reserver.AddnewcardActivity;
import com.uenpay.oem.ui.verifyinput.VerifyInputActivity;
import com.uenpay.oem.util.BankCardUtil;
import com.uenpay.oem.widget.dialog.BankCardListDialog;
import com.uenpay.oem.widget.dialog.UenChooseDialog;
import com.uenpay.oem.widget.dialog.WithdrawDialog;
import com.uenpay.oem.widget.listener.AmountEditTextWatcher;
import com.uenpay.service.bean.BankCardInfo;
import com.uenpay.service.bean.TransBankCardList;
import com.uenpay.util.app.base.BaseActivity;
import com.uenpay.util.rx.CommonEvent;
import com.uenpay.util.rx.RxBus;

import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by PS on 2017/6/20.
 */

public class WithdrawActivity extends BaseActivity implements WithdrawContract.View {

	public static final int REQUEST_INPUT_PASSWORD = 201;

	@BindView(R.id.tv_bank_name)
	TextView tvBankName;
	@BindView(R.id.iv_bank_icon)
	ImageView ivBankLogo;
	@BindView(R.id.et_withdraw_money)
	EditText et_withdraw_money;
	@BindView(R.id.tv_usablemaney)
	TextView tvUsablemaney; // 可用余额
	@BindView(R.id.tv_All_withdrawal)
	TextView tvAllWithdrawal; // 全部提现
	@BindView(R.id.tv_poundage)
	TextView tvPoundage; // 手续费的收取
	private WithdrawContract.Presenter mWithdrawPresenter;
	private TransBankCardList<BankCardInfo> mTransBankCardList;
	private BankCardInfo recommendBankCard;
	private WithdrawDialog withdradialog;

	private String cardEndNum;
	private String balance;
	private int choosePosition;
	private UserTradePoundageInfo MUserTrade;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle("提现");
		balance = getIntent().getStringExtra("Balance");

		tvUsablemaney.setText(balance + "（元）");

		initData();

	}

	private void initData() {
		setPresenter(null);
		mWithdrawPresenter.getTransBankCardList();
		// et的监听
		et_withdraw_money.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
		et_withdraw_money.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

				et_withdraw_money.setFilters(new InputFilter[] { new InputFilter() {
					@Override
					public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
						if (dest.toString().length() > 7) {
							return "";
						}
						if (source.equals(".") && dest.toString().length() == 0) {
							return "0.";
						}
						if (dest.toString().contains(".")) {
							int index = dest.toString().indexOf(".");
							int mlength = dest.toString().substring(index).length();
							if (mlength == 3) {
								return "";
							}
						}
						return null;
					}
				} });
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (MUserTrade != null) {
					if (TextUtils.isEmpty(s.toString())) {
						tvPoundage.setText("收取" + MUserTrade.getTradeFee() + "%的提现手续费");
						tvPoundage.setTextColor(Color.GRAY);
					} else {
						int Poundage = (int) Math.round(Double.valueOf(MUserTrade.getTradeFee()) * Double.valueOf(s.toString()));
						double poundage1 = Double.valueOf(Poundage) / 100;
						// 减掉手续费后的金额
						tvPoundage.setText("额外扣除¥" + poundage1 + "手续费");
						tvPoundage.setTextColor(Color.GRAY);
						if ((Double.valueOf(s.toString()) > Double.valueOf(balance))) {
							tvPoundage.setText("输入金额超过零钱余额");
							tvPoundage.setTextColor(Color.RED);
						}

					}
				}

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});

	}

	@Override
	public View bindView() {
		return null;
	}

	@Override
	public int bindLayout() {
		return R.layout.activity_withdraw;
	}

	@Override
	public void initView(View view) {

	}

	boolean isOnAllmaney = false;

	@OnClick({ R.id.ll_bank, R.id.btn_withdraw, R.id.tv_All_withdrawal })
	public void onClick(View view) {
		switch (view.getId()) {
		// 选择银行卡
		case R.id.ll_bank:
			if (mTransBankCardList != null && mTransBankCardList.getBankCardList().size() > 0) {
				final BankCardListDialog dialog = new BankCardListDialog(WithdrawActivity.this, mTransBankCardList, choosePosition);
				dialog.setonaddlistener(new BankCardListDialog.onaddclickListenner() {
					@Override
					public void onaddclick() {
						Intent intent = new Intent(WithdrawActivity.this, AddnewcardActivity.class);
						startActivity(intent);
						dialog.dismiss();
					}
				});
				// 点击关闭
				dialog.setoncloseListener(new BankCardListDialog.oncloseclickListener() {
					@Override
					public void oncloseClick() {
						dialog.dismiss();
					}
				});

				dialog.setOnChooseBankListener(new BankCardListDialog.OnChooseBankListener() {
					@Override
					public void choose(int position) {
						recommendBankCard = mTransBankCardList.getBankCardList().get(position);
						choosePosition = position;
						initBankview();
					}
				});

				dialog.show();

			}

			break;

		// 点击下一步
		case R.id.btn_withdraw:

			String amount = et_withdraw_money.getText().toString();
			if (TextUtils.isEmpty(amount)) {
				ToastUtil.showToast(this, "请输入提现金额");
				return;
			}
			if (Double.valueOf(amount) > Double.valueOf(balance)) {
				ToastUtil.showToast(this, "余额不足 请重新输入金额");
				return;
			}
			if (Double.valueOf(amount) < Double.valueOf(MUserTrade.getMinAmountLimit())) {
				ToastUtil.showToast(this, "最小输入金额为" + MUserTrade.getMinAmountLimit());
				return;
			}
			if (Double.valueOf(amount) > Double.valueOf(MUserTrade.getMaxAmountLimit())) {
				ToastUtil.showToast(this, "最大输入金额为" + MUserTrade.getMaxAmountLimit());
				return;
			}
			if (recommendBankCard != null) {
				showWithdraw(amount);
			}

			break;

		case R.id.tv_All_withdrawal:
			isOnAllmaney = true;
			if(Double.valueOf(balance)<=0.0){
				ToastUtil.showToast(this,"余额不能为空");
				return;
			}

			if (MUserTrade != null) {
				int Poundage = (int) Math.round(Double.valueOf(MUserTrade.getTradeFee()) * Double.valueOf(balance));
				double poundage1 = Double.valueOf(Poundage) / 100;
				// 减掉手续费后的金额
				double maney = Double.valueOf(balance) - poundage1;
				DecimalFormat df = new DecimalFormat(".##");
				String st = df.format(maney);
				et_withdraw_money.setText(st);
				tvPoundage.setText("额外扣除¥" + poundage1 + "手续费");
				tvPoundage.setTextColor(Color.GRAY);
			}
			break;
		}
	}

	/**
	 * 输入支付密码
	 */
	private void showWithdraw(String amount) {
		if (TextUtils.isEmpty(MUserTrade.getTradeFee())) {
			ToastUtil.showToast(this, "尚未获取费率...");

			return;
		}
		int Poundage = (int) Math.round(Double.valueOf(MUserTrade.getTradeFee()) * Double.valueOf(amount));
		Intent intent = new Intent(WithdrawActivity.this, VerifyInputActivity.class);
		intent.putExtra("title", "请输入支付密码");
		intent.putExtra("amount", et_withdraw_money.getText().toString().trim());
		intent.putExtra("forget_pwd", true);
		intent.putExtra("show_pwd", false);
		intent.putExtra("input_length", 6);
		intent.putExtra("desc", "额外扣除¥" + Double.valueOf(Poundage) / 100 + " 手续费");
		startActivityForResult(intent, REQUEST_INPUT_PASSWORD);
	}

	/**
	 * 网络获取下数据
	 *
	 * @param list
	 */
	@Override
	public void setTransBankCardList(TransBankCardList<BankCardInfo> list) {
		mTransBankCardList = list;
		recommendBankCard = mTransBankCardList.getBankCardList().get(0);
		initBankview();
	}

	@Override
	public void poundageSucced(boolean result) {
		if (result) {
			Intent intent = new Intent(WithdrawActivity.this, WithdrawsucceedActivity.class);
			// 金额
			intent.putExtra("withdrawmaney", et_withdraw_money.getText().toString());
			// 银行卡信息
			intent.putExtra("tank", recommendBankCard.getBankName() + "   (" + cardEndNum + ")");
			intent.putExtra("setpoundage", MUserTrade.getTradeFee());
			startActivity(intent);
			RxBus.$().post(MyFragment.TAG, new CommonEvent(RxBusEventConstant.EVENT_RECHARGE_SUCCESS));
			RxBus.$().post(HomeNewFragment.TAG, new CommonEvent(RxBusEventConstant.EVENT_RECHARGE_SUCCESS));
			finish();
		} else {

			final UenChooseDialog uenChooseDialog = new UenChooseDialog(this, WithdrawActivity.this);
			uenChooseDialog.setMessage("支付密码不正确，请重试");
			uenChooseDialog.setOnCancleClickListener(new UenChooseDialog.OnCancleListener() {

				@Override
				public void onCancle() {
					Intent intent = new Intent(WithdrawActivity.this, SetPayPwdActivity.class);
					startActivity(intent);
					uenChooseDialog.dismiss();
				}
			});
			uenChooseDialog.setOnConfirmClickListener(new UenChooseDialog.OnConfirmListener() {

				@Override
				public void onConfirm() {
					showWithdraw(et_withdraw_money.getText().toString().trim());
					uenChooseDialog.dismiss();
				}
			});
			uenChooseDialog.show();
		}

	}

	@Override
	public void getpoundage(UserTradePoundageInfo poundage) {
		MUserTrade = poundage;

	}

	private void initBankview() {
		ivBankLogo.setVisibility(View.VISIBLE);
		ivBankLogo.setImageResource(BankCardUtil.getLogoByBankName(recommendBankCard.getBankName()));
		String cardNum = recommendBankCard.getCardNo();
		cardEndNum = cardNum.substring(cardNum.length() - 4);
		tvBankName.setText(recommendBankCard.getBankName() + "   (" + cardEndNum + ")");

		// 请求成功后将银行卡的类别传给服务器
		mWithdrawPresenter.getPoundagemaney(AppConstant.TradeType.WITHDRAW);

	}

	@Override
	public void showLoading() {
	}

	@Override
	public void dismissLoading() {

	}

	@Override
	public void setPresenter(Object presenter) {
		mWithdrawPresenter = new WithdrawPresenter(this);
	}

	@Override
	public void showToast(String msg) {
		Toasts.shortToast(this, msg);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK)
			return;
		if (requestCode == REQUEST_INPUT_PASSWORD) {
			String pwd = data.getStringExtra("pwd");
			if (!isOnAllmaney) {
				// 获取paytoen
				mWithdrawPresenter.getpayToen(pwd, Double.valueOf(balance), recommendBankCard.getUserBankId() + "");
			} else {
				// 获取paytoen

				mWithdrawPresenter.getpayToen(pwd, Double.valueOf(et_withdraw_money.getText().toString()),
						recommendBankCard.getUserBankId() + "");
			}
		}
	}
}
